<template>
  <div class="app-container">
    <el-form ref="formSearch" :model="searchForm" label-width="100px">
      <el-row>
        <el-col :span="19">
          <el-row class="form_table">
            <el-col :span="6">
              <el-form-item :label="$t('user.username')" prop="username">
                <el-input v-model.trim="searchForm.username" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('user.nickname')" prop="nickname">
                <el-input v-model.trim="searchForm.nickname" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('user.phone')" prop="phone">
                <el-input v-model.trim="searchForm.phone" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('businessGlossary.enabled')" prop="enabled">
                <el-select v-model="searchForm.enabled" :placeholder="$t('placeholder.select')" clearable>
                  <el-option v-for="item in $enableDict" :key="item.id" :label="item.text" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="5" style="text-align: center">
          <el-button
            type="primary"
            @click="
              searchForm.pageNumber = 1
              getData()
            "
          >{{ $t('btn.query') }}</el-button>
          <el-button type="danger" @click="resetForm('formSearch')">{{ $t('btn.reset') }}</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-button v-permission="'gaeaUserController#insert'" type="primary" icon="el-icon-plus" @click="openCreateUser">{{ $t('btn.add') }}</el-button>
    <el-button v-permission="'gaeaUserController#update'" type="primary" icon="el-icon-edit" :disabled="selectedList.length != 1" @click="editDetail('edit', null)">{{ $t('btn.edit') }}</el-button>
    <el-button v-permission="'gaeaUserController#saveRoleTree'" type="primary" icon="el-icon-edit" :disabled="selectedList.length != 1" @click="setRole">{{ $t('user.setRole') }}</el-button>
    <el-button v-permission="'gaeaUserController#resetPassword'" type="warning" icon="el-icon-warning" :disabled="selectedList.length != 1" @click="resetPsw">{{ $t('user.resetPsw') }}</el-button>
    <el-button v-permission="'gaeaUserController#unLock'" type="primary" icon="el-icon-warning" :disabled="selectedList.length == 0" @click="unLock">{{ $t('user.unLock') }}</el-button>
    <el-button v-permission="'gaeaUserController#unLock'" type="primary" icon="el-icon-warning" @click="nickReFresh">{{ $t('user.nickReFresh') }}</el-button>
    <delete-btn v-permission="'gaeaUserController#deleteById'" :disabled="selectedList.length < 1" @handleDelete="handleDelete" />
    <el-table stripe :data="tableList" border @selection-change="handleSelectionChange">
      <el-table-column fixed type="selection" width="50" center />
      <el-table-column :label="$t('user.username')" min-width="110" align="center">
        <template slot-scope="scope">
          <span class="view" @click="editDetail('view', scope.row)">{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="nickname" :label="$t('user.nickname')" min-width="110" align="center" />
      <el-table-column prop="phone" :label="$t('user.phone')" min-width="110" align="center" />
      <el-table-column prop="email" :label="$t('user.email')" min-width="180" align="center" />
      <el-table-column prop="enabledStr" :label="$t('businessGlossary.enabled')" min-width="90" align="center" />
      <el-table-column prop="multiLoginStr" :label="$t('user.multiLogin')" min-width="90" align="center" />
      <el-table-column prop="createTime" :label="$t('businessGlossary.creationTime')" align="center" min-width="140" />
      <el-table-column prop="createByView" :label="$t('businessGlossary.creator')" align="center" min-width="100" />
      <el-table-column prop="updateTime" :label="$t('businessGlossary.modifyTime')" align="center" min-width="140" />
      <el-table-column prop="updateByView" :label="$t('businessGlossary.modifyUser')" align="center" min-width="100" />
    </el-table>
    <el-pagination v-show="total > 0" background :current-page.sync="searchForm.pageNumber" :page-sizes="$pageSizeAll" :page-size="searchForm.pageSize" layout="total, prev, pager, next, jumper, sizes" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <el-dialog :title="$t(`btn.${dialogTittle}`)" width="50%" :close-on-click-modal="false" center :visible.sync="basicDialog" @close="closeDialog">
      <el-form ref="userForm" :model="dialogForm" :rules="formRules" label-width="120px" :disabled="dialogTittle == 'view'">
        <el-row class="form_table">
          <el-col :span="12">
            <el-form-item :label="$t('user.username')" prop="username">
              <el-input v-model.trim="dialogForm.username" clearable :disabled="dialogTittle != 'add'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('user.nickname')" prop="nickname">
              <el-input v-model.trim="dialogForm.nickname" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('user.phone')" prop="phone">
              <el-input v-model.trim="dialogForm.phone" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('user.email')" prop="email">
              <el-input v-model.trim="dialogForm.email" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('businessGlossary.enabled')" prop="enabled">
              <anji-select v-model="dialogForm.enabled" :placeholder="$t('placeholder.select')" url="/business/gaeaDict/select/ENABLE_FLAG" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('user.multiLogin')" prop="enabled">
              <anji-select v-model="dialogForm.multiLogin" url="/business/gaeaDict/select/ENABLE_FLAG" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button v-if="dialogTittle != 'view'" type="primary" plain @click="confirm">{{ $t('btn.confirm') }}</el-button>
        <el-button type="danger" plain @click="basicDialog = false">{{ $t('btn.close') }}</el-button>
      </div>
    </el-dialog>
    <set-role :id="id" :visib="treeDialog" @handleClose="treeDialog = false" />
  </div>
</template>
<script>
import { getUserList, addUser, editUser, deleteUsers, resetPwd, unLock, userDetail, freshUsername } from '@/api/authority'
export default {
  name: 'User',
  components: {
    SetRole: require('./components/SetRole').default,
  },
  data() {
    return {
      id: '',
      treeDialog: false,
      selectedList: [],
      searchForm: {
        username: null,
        nickname: null,
        phone: null,
        enabled: null,
        pageNumber: 1,
        pageSize: 10,
      },
      tableList: [],
      total: 0,
      dialogTittle: 'view',
      basicDialog: false,
      dialogForm: {},
      formRules: {
        username: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        nickname: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        phone: [
          { required: false, message: this.$t('placeholder.input'), trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: this.$t('user.mobileValid'), trigger: 'blur' },
        ],
        email: [{ pattern: /^([a-zA-Z\d])(\w|\-)+@\S+\.[a-zA-Z]{2,4}$/, message: this.$t('user.validEmail'), trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 重置密码
    async resetPsw() {
      const usernames = this.selectedList.map((item) => item.username)
      resetPwd(usernames)
    },
    // 分配角色
    setRole() {
      this.id = this.selectedList[0].username
      this.treeDialog = true
    },

    nickReFresh() {
      const selectedList = this.selectedList
      let usernames = []
      if (selectedList.length > 0) {
        usernames = selectedList.map((item) => item.username)
      }
      freshUsername(usernames)
    },
    // 提交按钮
    confirm() {
      this.$refs.userForm.validate(async(valid, obj) => {
        if (valid) {
          if (this.dialogTittle == 'add') {
            const { code } = await addUser(this.dialogForm)
            if (code != '200') return
            this.closeDialog(true)
          } else {
            const { code } = await editUser(this.dialogForm)
            if (code != '200') return
            this.closeDialog(true)
          }
        } else {
          return
        }
      })
    },
    // 关闭弹窗
    closeDialog(bool) {
      bool && this.getData() // 点确定关闭弹窗的时候才会刷新列表
      this.$refs['userForm'].resetFields()
      this.basicDialog = false
    },

    unLock() {
      const usernames = this.selectedList.map((item) => item.username)
      unLock(usernames)
    },
    // 删除操作
    async handleDelete() {
      const ids = this.selectedList.map((item) => item.id)
      const { code } = await deleteUsers(ids)
      // const { code } = await deleteUser(this.selectedList[0].id) // 暂时保留单删接口
      if (code != '200') return
      this.getData()
    },
    // 新建操作
    openCreateUser() {
      this.dialogTittle = 'add' // 新建
      this.basicDialog = true
    },
    // 编辑和查看操作
    editDetail(title, row) {
      this.dialogTittle = title
      this.$nextTick(() => {
        userDetail(this.selectedList[0].id, this.selectedList[0].accessKey).then((res) => {
          this.dialogForm = res.data
          this.dialogForm.email = null
          this.dialogForm.phone = null
          this.basicDialog = true
        })
      })
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.tableList = []
      this.total = 0
      this.getData()
    },
    // 查询
    async getData() {
      const params = {
        ...this.searchForm,
        sort: 'update_time',
        order: 'DESC',
      }
      const { data, code } = await getUserList(params)
      if (code != '200') return
      this.tableList = data.records
      this.total = data.total
    },
    // 选择项改变时
    handleSelectionChange(val) {
      this.selectedList = val
    },
    // 页码改变
    handleCurrentChange(pageNumber) {
      this.searchForm.pageNumber = pageNumber
      this.getData()
    },
    // 每页size改变时
    handleSizeChange(val) {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = val
      this.getData()
    },
  },
}
</script>
